package pnu.ssm.sbmother;

import java.io.*;
import java.util.*;

import pnu.ssm.http.*;
import pnu.ssm.key.*;
import android.app.*;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.*;
import android.content.pm.*;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.*;
import android.support.v4.app.*;
import android.util.*;

import com.google.android.gms.common.*;
import com.google.android.gms.gcm.*;

public class MainActivity extends FragmentActivity {
	public static final String TAG = "MainActivity";
	private final boolean Debug = true;
	
	public static final String EXTRA_MESSAGE = "message";
	public static final String PROPERTY_REG_ID = "registration_id";
	private static final String PROPERTY_APP_VERSION = "appVersion";
	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	private String SENDER_ID = "770124100954";

	private GoogleCloudMessaging gcm;
	private SharedPreferences pref;
	private SharedPreferences.Editor editor;
	private Context context;
	private String regid;
	private HttpConnectorParent connectorParent;
	
	private String child_type = "PHONE";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		buildUI();
		setUpGCMServer();
	}

	private void buildUI() {
		this.context = this;
		this.pref = getSharedPreferences(Key.prefKey, MODE_PRIVATE);
		this.editor = pref.edit();
		
		child_type = getIntent().getStringExtra("child_type");
		
		connectorParent = HttpConnectorParent.getInstance();
		
		FragmentManager manager = getFragmentManager();
		Fragment fragment = new AndroidAppTab();
		FragmentTransaction transaction = manager.beginTransaction();
		transaction.add(R.id.main, fragment);
		transaction.show(fragment);
		transaction.commit();
	}
	
	private void setUpGCMServer(){
		if (checkPlayServices()) {
	    	Log.i(TAG,"has api of play services");
	    	gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(context);
            if (regid == "" || regid == null) 
            	registerInBackground();
            Log.e(TAG, "regID : "+regid);
	    }else{
	    	Log.e(TAG, "No valid Google Play Services APK found.");
	    }	
	}

	private boolean checkPlayServices() {
		if (Debug)
			Log.i(TAG, "checkPlayServices()");
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Log.i(TAG, "This device is not supported.");
				finish();
			}
			return false;
		}
		return true;
	}

	private String getRegistrationId(Context context) {
		if (Debug)
			Log.i(TAG, "getRegistrationId()");
		final SharedPreferences prefs = getGCMPreferences(context);
		String registrationId = prefs.getString(PROPERTY_REG_ID, "");
		if (registrationId == "" || registrationId == null) {
			Log.i(TAG, "Registration not found.");
			return "";
		}
		int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
				Integer.MIN_VALUE);
		int currentVersion = getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Log.i(TAG, "App version changed.");
			return "";
		}
		return registrationId;
	}

	/**
	 * @return Application's {@code SharedPreferences}.
	 */
	private SharedPreferences getGCMPreferences(Context context) {
		if (Debug)
			Log.i(TAG, "getGCMPreferences()");
		return getSharedPreferences(MainActivity.class.getSimpleName(),
				Context.MODE_PRIVATE);
	}

	/**
	 * @return Application's version code from the {@code PackageManager}.
	 */
	private static int getAppVersion(Context context) {
		Log.i(TAG, "getAppVersion()");
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	private void registerInBackground() {
		new AsyncTask<String, Void, String>() {
			@Override
			protected String doInBackground(String... params) {
				String msg = "";
				try {
					if (Debug)
						Log.i(TAG, "registerInBackground()");
					if (gcm == null)
						gcm = GoogleCloudMessaging.getInstance(context);
					regid = gcm.register(SENDER_ID);
					msg = "Device registered, registration ID=" + regid;
					sendRegistrationIdToBackend();
					storeRegistrationId(context, regid);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
				}
				return msg;
			}

			@Override
			protected void onPostExecute(String result) {
				// 3rd Party Server에 ID 등록 후에 작동할 코드.
			}

			private void sendRegistrationIdToBackend() {
				// Your implementation here.
				if (Debug) Log.e(TAG, "sendRegistrationIdToBackend()");
				
				String parent_num = pref.getString(Key.parent_num, null);
				
				String result = connectorParent.sendRegistrationID(parent_num, regid);
				
				if(result == null){
					Log.e(TAG, "fail to register");
				}else{
					Log.d(TAG, "success to register");
				}
			}
		}.execute(null, null, null);
	}

	private void storeRegistrationId(Context context, String regId) {
		if (Debug)
			Log.i(TAG, "storeRegistrationId()");
		final SharedPreferences prefs = getGCMPreferences(context);
		int appVersion = getAppVersion(context);
		Log.i(TAG, "Saving regId on app version " + appVersion);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(PROPERTY_REG_ID, regId);
		editor.putInt(PROPERTY_APP_VERSION, appVersion);
		editor.commit();
		
		//call personal editor
		this.editor.putString("reg_id", regId);
		this.editor.commit();
	}
}
